package com.sz.common.base.utils;

import com.sz.common.base.dto.TreeNode;
import org.apache.commons.collections.CollectionUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * Function: TreeBuilder <br>
 * Author: wentao.chang <br>
 * Date: 2016-10-31 15:11:00
 */
public class TreeBuilder {

    public static List<TreeNode> buildListToTree(List<TreeNode> nodes) {
        if (nodes == null) {
            return null;
        }
        List<TreeNode> roots = findRoots(nodes);
        @SuppressWarnings("unchecked")
        List<TreeNode> notRoots = (List<TreeNode>) CollectionUtils.subtract(nodes, roots);
        for (TreeNode root : roots) {
            root.setChildren(findChildren(root, notRoots));
        }
        return roots;
    }

    private static List<TreeNode> findRoots(List<TreeNode> allTreeNodes) {
        List<TreeNode> results = new ArrayList<TreeNode>();
        for (TreeNode treeNode : allTreeNodes) {
            boolean isRoot = true;
            for (TreeNode comparedOne : allTreeNodes) {
                if (treeNode.getParentId() == comparedOne.getId()) {
                    isRoot = false;
                    break;
                }
            }
            if (isRoot) {
                results.add(treeNode);
            }
        }
        return results;
    }

    private static List<TreeNode> findChildren(TreeNode root, List<TreeNode> allTreeNodes) {
        List<TreeNode> children = new ArrayList<TreeNode>();

        for (TreeNode comparedOne : allTreeNodes) {
            if (comparedOne.getParentId() == root.getId()) {
                children.add(comparedOne);
            }
        }
        @SuppressWarnings("unchecked")
        List<TreeNode> notChildren = (List<TreeNode>) CollectionUtils.subtract(allTreeNodes, children);
        for (TreeNode child : children) {
            List<TreeNode> tmpChildren = findChildren(child, notChildren);
            child.setChildren(tmpChildren);
        }
        return children;
    }
}
